package rpcserver;

import rpcservicetask.ServiceTask;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcServerCenter {
	
	private static final Map<String,Class> serverCenter=new HashMap<String,Class>();	
	
	private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
	private static int port;
	
	public RpcServerCenter(int port){
		this.port=port;
	}
	
    public void register(Class serviceInterface, Class impl) {
		  serverCenter.put(serviceInterface.getName(), impl);
	    }
    
    public static Class getServiceClass(String className){
    	return serverCenter.get(className);
    }
	 
    public void start(){
    	 ServerSocket server;
		try {
			 server = new ServerSocket();
			 server.bind(new InetSocketAddress(port));
	         System.out.println("start server success");
	         try {
	             while (true) {
	                 // 1.�����ͻ��˵�TCP���ӣ��ӵ�TCP���Ӻ����װ��task�����̳߳�ִ��
	                 executor.execute(new ServiceTask(server.accept()));
	             }
	         } finally {
	             server.close();
	         }
			
		} catch (IOException e) {
			e.printStackTrace();
		}
        
    }
    
    public  static void main(String[]args){
    	new RpcServerCenter(8080).start();
    }

}
